package com.ruiboyun.liveapp.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ruiboyun.liveapp.R;
import com.ruiboyun.liveapp.base.BaseActivity;
import com.ruiboyun.liveapp.bean.Channel;
import com.ruiboyun.liveapp.bean.Share;
import com.ruiboyun.liveapp.dialog.BaseDialog;
import com.ruiboyun.liveapp.dialog.SharePopupWindow;
import com.ruiboyun.liveapp.util.sys.ScreenInfo;
import com.ruiboyun.liveapp.util.tool.ToasUtil;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class LiveActivity extends BaseActivity implements LiveManager.OnLiveListener {

    @Bind(R.id.surface_view)
    SurfaceView surfaceView;
    @Bind(R.id.container)
    RelativeLayout container;
    @Bind(R.id.camera_facing)
    CheckBox cameraFacing;
    @Bind(R.id.beauty)
    CheckBox beauty;
    @Bind(R.id.flash)
    CheckBox flash;
    @Bind(R.id.open)
    CheckBox open;
    @Bind(R.id.share)
    ImageView share;
    @Bind(R.id.close)
    ImageView close;
    @Bind(R.id.tips)
    TextView tips;
    @Bind(R.id.time)
    TextView time;
    private String url;
    private Channel channel;


    public static void go(Context context, String json) {
        Intent intent = new Intent(context, LiveActivity.class);
        intent.putExtra("json", json);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    protected void afterCreate(@Nullable Bundle savedInstanceState) {
      /*  ViewGroup.LayoutParams layoutParams = container.getLayoutParams();
        layoutParams.height= ScreenInfo.getWidth(this)*9/16;
        container.setLayoutParams(layoutParams);*/
        String json = getIntent().getStringExtra("json");
        channel = JSON.parseObject(json, Channel.class);
        LiveManager.getInstance().setOnLiveListener(this);
        LiveManager.getInstance().init(channel.getRtmp_addr(),channel);

        LiveManager.getInstance().startPreview(surfaceView);
        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LiveManager.getInstance().autoFocus(event.getX(), event.getY());
                return false;
            }
        });
    }

    @OnCheckedChanged({R.id.open, R.id.camera_facing, R.id.beauty, R.id.flash})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.open:
                if (isChecked) {
                    buttonView.setText("停止直播");
                    tips.setText("直播开启中。。。");
                    LiveManager.getInstance().startLive(channel.getRtmp_addr());
                } else {
                    reset();
                    buttonView.setText("开始直播");
                    tips.setText("");
                    LiveManager.getInstance().stopLive();
                }
                break;
            case R.id.camera_facing:

                LiveManager.getInstance().switchCamera();
                break;
            case R.id.beauty:
                LiveManager.getInstance().switchBeauty(isChecked);
                break;
            case R.id.flash:
                break;

        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (open.isChecked()){
            if (open.isChecked()) {
                BaseDialog baseDialog = new BaseDialog(this);
                baseDialog.setContent("不在播会儿吗？")
                        .setConfirmText("继续")
                        .setCancleText("退出")
                        .show();
                baseDialog.setOnConfirmListener(new BaseDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {

                    }

                    @Override
                    public void onCancle() {
                        reset();
                        LiveManager.getInstance().reset();
                       finish();
                    }
                });
            }
        }else {
            reset();
            LiveManager.getInstance().reset();
           finish();
        }
    }

    @OnClick({R.id.share, R.id.close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share:
                Share share = new Share();
                share.setTitle(channel.getTitle());
                share.setContent(channel.getDesc());
                share.setUrl(channel.getPlay_addr());
                share.setLogo(channel.getCover_addr());
                SharePopupWindow sharePopupWindow = new SharePopupWindow(this, share);
                sharePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.close:
                if (open.isChecked()) {
                    BaseDialog baseDialog = new BaseDialog(this);
                    baseDialog.setContent("不在播会儿吗？")
                            .setConfirmText("继续")
                            .setCancleText("退出")
                            .show();
                    baseDialog.setOnConfirmListener(new BaseDialog.OnConfirmListener() {
                        @Override
                        public void onConfirm() {

                        }

                        @Override
                        public void onCancle() {
                            reset();
                            LiveManager.getInstance().reset();
                            finish();
                        }
                    });
                } else {
                    reset();
                    LiveManager.getInstance().reset();
                    finish();
                }


                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int duration = msg.arg1;
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    message.arg1 = duration + 1;
                    handler.sendMessageDelayed(message, 1000);

                    int second = duration % 60;
                    int minute = duration / 60 % 60;
                    int hour = duration / 3600;
                    time.setText(getTime(hour) + ":" + getTime(minute) + ":" + getTime(second));

                    break;
            }
        }
    };

    public String getTime(int time) {
        if (time < 10) {
            return "0" + time;
        } else {
            return String.valueOf(time);
        }
    }

    @Override
    public void onError(String msg) {
        tips.setText(msg);
        reset();
    }

    private void reset() {
        handler.removeMessages(1);
        time.setText("00:00:00");
    }

    @Override
    public void onNetBroken() {
        open.setChecked(false);
        ToasUtil.showCenterToast("网络卡顿，直播已停止!");
    }

    @Override
    public void onLive() {
        Message message = handler.obtainMessage();
        message.what = 1;
        message.arg1 = 0;
        handler.sendMessage(message);
        tips.setText("直播中。。。");
    }
}
